<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select v-model="query.name" clearable size="small" placeholder="团队名称" class="filter-item" style="width: 120px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select v-model="query.websiteName" v-permission="['admin','sysWebsiteManage:list']" clearable size="small" placeholder="网站名称" class="filter-item" style="width: 120px" @change="crud.toQuery">
          <el-option v-for="item in websiteList" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select v-model="query.accountStatus" clearable size="small" placeholder="账号状态" class="filter-item" style="width: 120px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-select v-model="query.cooperationStatus" clearable size="small" placeholder="合作状态" class="filter-item" style="width: 120px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-input v-model="form.name" class="filter-item" style="width: 170px; float: right ;" placeholder="请输入搜索的信息" suffix-icon="el-icon-search" />

        <!-- <rrOperation /> -->
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation show="" :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="团队名称" prop="name">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="用户名" prop="name">
            <el-input v-model="form.userName" style="width: 370px;" />
          </el-form-item>
          <div v-for="(item,index) in form.teamDetails" :key="index" class="addTeam">
            <el-form-item v-permission="['admin','sysWebsiteManage:list']" label="关联网站">
              <el-select v-model="item.websiteId" clearable size="small" placeholder="网站名称" class="filter-item" style="width: 120px" @change="crud.toQuery">
                <el-option v-for="items in websiteList" :key="items.maintainerId" :label="items.maintainerName" :value="items.maintainerId" />
              </el-select>
            </el-form-item>
            <el-form-item v-permission="['admin','user:list']" label="维护人">
              <el-select v-model="item.maintainerId" clearable size="small" placeholder="维护人" class="filter-item" style="width: 120px" @change="crud.toQuery">
                <el-option v-for="items in maintainList" :key="items.maintainerId" :label="items.maintainerName" :value="items.maintainerId" />
              </el-select>
            </el-form-item>
            <div class="Additem">
              <i v-show="index > 0" class="el-icon-circle-close" style="cursor: pointer;" @click="deleteItem(index)" />
              <i
                v-show="index == form.teamDetails.length - 1"
                class="el-icon-circle-plus-outline"
                style="margin-left: 5px; color: #08c81b; cursor: pointer;"
                @click="addItem()"
              />
            </div>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="button_left" type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" :span-method="objectSpanMethod" style="width: 100%;" border @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column prop="name" label="团队名称" align="center" />
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="websiteName" label="关联网站" align="center" />
        <el-table-column prop="maintainerName" label="维护人" align="center" />
        <el-table-column prop="cooperationStatus" align="center" label="合作状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.cooperationStatus"
              active-color="#4d75cc"
              inactive-color="#E9EBF2"
              active-value="0"
              inactive-value="1"
              @change="changeEnabled(scope.row, scope.row.cooperationStatus)"
            />
            <div class="settle" @click="settleEdit">结算设置</div>
          </template>
        </el-table-column>
        <el-table-column prop="accountStatus" align="center" label="账号状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.accountStatus"
              active-color="#4d75cc"
              inactive-color="#E9EBF2"
              active-value="0"
              inactive-value="1"
              @change="changeEnabled(scope.row, scope.row.accountStatus)"
            />
          </template>
        </el-table-column>
        <el-table-column min-width="120px" label="设备限制" align="center">
          <template slot-scope="{row}">
            <div class="finger-container">
              <editable-cell
                v-model="row.deviceLimit"
                :show-input="row.editMode"
                @keyup.enter.native="upDateFingerCount(row)"
              >
                <span slot="content" class="content">{{ row.deviceLimit }}</span>
              </editable-cell>
              <p class="finger-delete" @click="clearFinger(row)">清空</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" align="center" />
        <el-table-column prop="createAt" label="添加时间" align="center" />

        <el-table-column v-if="checkPer(['admin','sysWebsiteManage:edit','sysWebsiteManage:del'])" label="操作" width="150px" align="center" fixed="right">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <!-- <pagination /> -->
      <clearingSetup ref="clearingSetup" />
    </div>
  </div>
</template>

<script>
import { initData_New } from '@/api/data'
import clearingSetup from './clearingSetup'
import crudJob from '@/api/people/Team/index'
import crudSysWebsiteManage from '@/api/people/Team/index'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import pagination from '@crud/Pagination'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'

const defaultForm = { id: undefined, name: undefined, creatorId: undefined, createAt: undefined, updateAt: undefined, isDelete: undefined, deptId: undefined, teamDetails: [{ maintainerId: '', websiteId: '' }] }
export default {
  name: 'SysWebsiteManage',
  components: { crudOperation, udOperation, clearingSetup },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['isDelete_status'],
  cruds() {
    return CRUD({ title: '/修改网站', url: 'api/platform-team', idField: 'id', sort: 'id,desc', crudMethod: { ...crudSysWebsiteManage },
      optShow: {
        add: true,
        edit: false,
        del: false,
        reset: false
      }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'platformTeam:add'],
        edit: ['admin', 'platformTeam:edit'],
        del: ['admin', 'platformTeam:del']
      },
      rules: {
        name: [
          { required: true, message: '团队名称不能为空', trigger: 'blur' }
        ]
      },
      enabledTypeOptions: [{}],
      maintainList: [], // 维护人数组
      websiteList: [], // 关联网站数组
      spanArr: [], // 需要合并的行数
      pos: 0 // 索引
    }
  },
  created() {
    this.getSpanArr()
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 改变状态
    changeEnabled(data, val) {
      // const vals = Number(val)
      console.log('1111', data, val, this.dict.label.isDelete_status)
      this.$confirm('此操作将 "' + this.dict.label.isDelete_status[val] + '" ' + data.name + '岗位, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // eslint-disable-next-line no-undef
        crudJob.edit(data).then(() => {
          // eslint-disable-next-line no-undef
          this.crud.notify(this.dict.label.isDelete_status[val] + '成功', 'success')
        }).catch(err => {
          data.enabled = !data.enabled
          console.log(err.data.message)
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 删除
    deleteItem(index) {
      this.form.teamDetails.splice(index, 1)
    },
    // 添加
    addItem() {
      this.form.teamDetails.push({ maintainerId: '', websiteId: '' })
      // form.log(defaultForm)
    },
    // 获取合并行列的个数
    getSpanArr() {
      initData_New('api/platform-team').then(data => {
        console.log(data)
        for (let i = 0; i < data.length; i++) {
        // 如果是第一个数据，就将列表spanArr添加一个1，表示暂时只有一个名字相同的、且将索引pos赋值为0
          if (i === 0) {
            this.spanArr.push(1)
            this.pos = 0
          } else {
          // 判断当前元素与上一个元素是否相同
            if (data[i].teamId === data[i - 1].teamId) {
            // 如果相同就将索引为 pos 的值加一
              this.spanArr[this.pos] += 1
              // 且将数组添加 0
              this.spanArr.push(0)
            } else {
            // 如果元素不同了，就可以通过索引为 pos 的值知晓应该需要合并的行数
            // 同时，我们再次添加一个值1，表示重新开始判断重复姓名的次数
              this.spanArr.push(1)
              // 同时 索引加一
              this.pos = i
            }
          }
        }
        console.log('索引数组：')
        console.log(this.spanArr)
        // 表格序号
        let numSort = 0
        for (const n in this.spanArr) {
          if (this.spanArr[n] > 0) {
            numSort += 1
            this.$set(this.form[n], 'numSort', numSort)
          }
        }
      })

      // console.log(this.crud, data, '111')
      // 遍历数据
    },
    // 改变行列合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 3 || columnIndex === 1 || columnIndex === 2) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // 新增前初始化维护人信息
    [CRUD.HOOK.beforeToAdd](crud, form) {
      initData_New('api/users/usernames').then(data => {
        this.maintainList = data
        // this.form = this.defaultForm
      })
      initData_New('api/website-manage/names').then(data => {
        this.websiteList = data
        // this.form = this.defaultForm
      })
    },
    settleEdit() {
      this.$refs.clearingSetup.open()
    }
  }
}
</script>

<style scoped lang="scss">
.dialog-footer{
  .button_left{
    margin-right: 20px;
  }
}
.addTeam{
  display: flex;
  margin-bottom: -10px;
}
// .aa >>> .el-form-item__content {
//    margin-left:0px !important;
// }
.Additem{
  width: 50px;
  height: 33px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.settle{
  display: inline;
  color: rgb(24,144,255);
}
</style>
